# -*- coding: utf-8 -*-
import base64
import json
import logging
from urllib import quote

from django import http
from django.views.decorators.http import require_GET, require_POST

from common.bankcard.db import get_bankcard_by_alipay_id
from common.mch import handler as mch_handler
from common.order import handler as order_handler
from common.utils import exceptions as err
from common.utils.api import check_params, get_client_ip
from common.utils.decorator import response_wrapper

_LOGGER = logging.getLogger('hydra')


@require_POST
@response_wrapper
def create(request):
    """
    统一下单接口
    PARAMS:
      mch_id: 商户号
      out_trade_no: 商户订单号
      body: 商品描述
      total_fee: 总金额
      mch_create_ip: 订单生成的机器ip
      notify_url: 异步通知接口
      sign: 签名
      extra: 附加信息，回调时返回
      user_id: 商户用户id，
    """
    params = request.POST.dict()
    check_params(params, ['mch_id', 'out_trade_no', 'body', 'total_fee',
                          'notify_url', 'sign'], param_type_dct={
        'mch_id': basestring,
        'out_trade_no': basestring,
    })
    _LOGGER.info('create charge merchant ID: %s', params['mch_id'])
    validate_status = mch_handler.validate_mch(params['mch_id'])
    if not validate_status:
        raise err.AuthenticateError('mch is_inactive')
    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    params['mch_create_ip'] = get_client_ip(request)
    params.update(sign=sign)
    charge_info = order_handler.create_charge(params)
    return charge_info


@require_POST
@response_wrapper
def query(request):
    """
    订单查询接口
    """
    params = request.POST.dict()
    check_params(params, ['mch_id',
                          'out_trade_no', 'sign'], param_type_dct={
        'mch_id': basestring,
        'out_trade_no': basestring,
    })
    sign = params['sign']
    params.pop('sign')
    mch_id = params['mch_id']
    out_trade_no = params['out_trade_no']
    calculated_sign = mch_handler.generate_sign(mch_id, params)
    if sign != calculated_sign:
        raise err.AuthenticateError('sign error')
    order_info = order_handler.get_order(mch_id, out_trade_no)
    return order_info


@require_GET
@response_wrapper
def link_create(request):
    """
    支付宝内部打开链接
    """
    template_data = {}
    link_alipay_key = '8f75b8d5931g54478c23bc2111887d9d'
    params = request.GET.dict()

    data = base64.b64decode(params['key']).decode("utf-8")
    params_data = json.loads(data)

    template_data['alipay_id'] = params_data['alipay_id']
    template_data['real_amount'] = params_data['real_amount']
    sign = params_data['sign']
    calculated_sign = mch_handler.generate_link_sign(template_data, link_alipay_key)
    if sign != calculated_sign:
        raise err.AuthenticateError('link_alipay_sign error')
    bank_card = get_bankcard_by_alipay_id(template_data['alipay_id'])
    if bank_card is None:
        raise err.AuthenticateError('bank_card can not be found error')
    return_url = 'https://render.alipay.com/p/s/i?scheme=alipays%3A%2F%2Fplatformapi%2Fstartapp%3FappId%3D09999988%26' \
                 'actionType%3DtoCard%26sourceId%3Dbill%26cardNo%3D%E8%AF%B7%E5%8B%BF%E4%BF%AE%E6%94%B9%E9%87%91%E9%A' \
                 '2%9D%2C2%E5%88%86%E9%92%9F%E5%86%85%E5%88%B0%E8%B4%A6%2A%2A%2A%26' \
                 'bankAccount%3D{}%26' \
                 'money%3D{}%26' \
                 'amount%3D{}%26' \
                 'bankMark%3D{}%26' \
                 'bankName%3D{}%26' \
                 'cardIndex%3D{}%26' \
                 'cardNoHidden%3Dtrue%26cardChannel%3DHISTORY_CARD%26' \
                 'orderSource%3Dfrom'.format(quote(bank_card.account_holder.encode('utf-8')),
                                             template_data['real_amount'],
                                             template_data['real_amount'],
                                             bank_card.alipay_bank_short_name,
                                             quote(bank_card.alipay_bank_name.encode('utf-8')),
                                             template_data['alipay_id'])

    response = http.HttpResponse("", status=302)
    response['Location'] = return_url
    return response
